/**
 * @Author: jipeng.Li
 * @Date: 2021-04-20 14:00:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-04-20 18:36:21
 * @Description: 核销列表
 */

import React, { Component } from 'react';
import { Image, NativeModules, SafeAreaView, StyleSheet, Text, TouchableOpacity, View, } from 'react-native';
import { BackImage, Header, msg } from '@/common';
import { fontColorBlack, fontColorCoffee, isAndroid, mainBgColorLightGray, px2dp } from '@/styles';
import { empty02, iconPositionCoffee, iconRightGray } from '@/images';
import EmptyPage from '@/components/EmptyPage';
import oil from '@/api/oil';
import tool from '@/common/utils/getDate';
import { calculatJD } from '@/common/utils/util';
import Moment from 'moment';
import XmList from '../../../components/XmList';
import WriteOffListItem from './components/write-off-list-item';

export default class WriteOffForOil extends Component {
  constructor(props) {
    super(props);
    this.state = {
      writeOffList: [],
      pageNo: 1,
      pageSize: 5,
      isLoading: false,
      showFoot: 1, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      siteDetails: null
    };
  }

  componentDidMount() {
    this.getCurrentPosition();
    msg.on('curStation', curStation => {
      this.setState({ siteDetails: curStation }, () => this.loadData());
    });
  }

  render() {
    const { writeOffList, isLoading, showFoot } = this.state;
    return (
      <SafeAreaView style={{ flex: 1 }}>
        {this._renderHead()}
        <View style={styles.titleTips}>
          <Text>请选择加油单据</Text>
          <TouchableOpacity
            style={styles.titleTips}
            onPress={() => {
              msg.emit('router: goToNext', {
                routeName: 'WriteOffRecord',
              });
            }}
          >
            <Text>核销记录</Text>
            <Image source={iconRightGray} style={styles.titleTipsRightImage} />
          </TouchableOpacity>
        </View>
        <XmList
          sources={writeOffList}
          renderItem={this._renderItem}
          style={styles.xmListContainer}
          isLoading={isLoading}
          onDropdownRefresh={this.loadData}
          onPullUpMore={this.LoadMore}
          singleKey={item => `writeOffList${item.id}`}
          showFoot={showFoot}
          customEmptyView={<EmptyPage emptyIcon={empty02} noText='附近暂无油站~' />}
        />
      </SafeAreaView>
    );
  }

  // 自定义头部
  _renderHead = () => {
    const { siteDetails } = this.state;
    return (
      <Header
        renderTitle={() => <Text style={styles.headTitleText}>加油核销</Text>}
        renderLeft={() => (
          <TouchableOpacity
            activeOpacity={0.8}
            onPress={this.goBack}
            style={
              isAndroid ?
                { paddingVertical: px2dp(14), paddingHorizontal: px2dp(40) } :
                { paddingVertical: px2dp(14), paddingRight: px2dp(40) }
            }
          >
            <BackImage />
          </TouchableOpacity>
        )}
        renderRight={() => {
          return (
            <TouchableOpacity
              onPress={() => {
                msg.emit('router: goToNext', {
                  routeName: 'AddOilLocale',
                });
              }}
              style={[
                styles.headRight,
                isAndroid ? { marginRight: 14 } : {}
              ]}
            >
              <Image
                style={styles.headRightImage}
                source={iconPositionCoffee}
              />
              <Text
                style={styles.headRightText}
                numberOfLines={1}
              >
                {siteDetails && siteDetails.siteName}
              </Text>
            </TouchableOpacity>
          );
        }}
      />
    );
  }

  goBack = () => {
    msg.emit('router: back');
  }

  _renderItem = ({ item }) => {
    let writeOffData = {
      加油金额: <Text style={{ color: fontColorCoffee, fontSize: px2dp(28) }}>{`￥${calculatJD(item.amount / 100)}`}</Text>,
      油品名称: <Text style={{ color: fontColorBlack }}>{item.gasType}</Text>,
      油品单价: <Text style={{ color: fontColorBlack }}>{`${calculatJD(item.price / 100)}元 / 升`}</Text>,
      加油升数: <Text style={{ color: fontColorBlack }}>{`${calculatJD(item.liter / 100)}L`}</Text>,
      加油枪号: <Text style={{ color: fontColorBlack }}>{`${item.gunNo}号`}</Text>,
      加油时间: <Text style={{ color: fontColorBlack }}>{Moment(item.createTime).format('YYYY.MM.DD hh:mm')}</Text>
    };
    return (
      <View style={{ marginBottom: px2dp(30) }}>
        <WriteOffListItem
          lineText={writeOffData}
          btnClick={() => {
            msg.emit('router: goToNext', {
              routeName: 'QRCodeScanCAV',
              isAlliance: true,
              verificationAuthority: true,
              oilcardAuthority: true,
              oilWriteOffData: {
                siteNo: item.siteNo,
                tcc: item.id,
                gunNo: item.gunNo,
                amount: item.amount,
                gasType: item.gasType,
                price: item.price,
                liter: item.liter,
                createTime: tool.dateForm(item.createTime, 'yy-MM-dd hh:mm:ss'),
              }
            });
          }}
        />
      </View>
    );
  }

  // 获取当前定位
  getCurrentPosition = () => {
    // 当前定位
    NativeModules.MapModule.getCurrentPosition().then(resPosition => {
      if (resPosition.city) {
        let longAndLat = { lat: resPosition.latitude, lgt: resPosition.longitude };
        oil.pageSite({ pageNo: 1, pageSize: 20, siteType: 2, ...longAndLat }).then(res => {
          if (res.success) {
            const { records = [] } = res.data;
            if (records.length) {
              this.setState({ siteDetails: records[0] }, () => this.loadData());
            } else {
              msg.emit('app:messageBox', {
                isVisible: true,
                title: '提 示',
                text: '附近油站获取失败',
                okText: '重试',
                cancelText: '取消',
                isClickBg: false,
                okFn: () => {
                  this.getCurrentPosition();
                },
                cancelFn: () => {
                  msg.emit('router: back');
                },
              });
            }
          } else {
            msg.emit('app:messageBox', {
              isVisible: true,
              title: '提 示',
              text: '附近油站获取失败',
              okText: '重试',
              cancelText: '取消',
              isClickBg: false,
              okFn: () => {
                this.getCurrentPosition();
              },
              cancelFn: () => {
                msg.emit('router: back');
              },
            });
          }
        });
      } else {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '提 示',
          text: '获取地理位置信息失败, 请开启GPS重试',
          okText: '确定',
          isClickBg: false,
          okFn: () => {
            msg.emit('router: back');
          },
        });
      }
    });
  };

  // 下拉刷新
  loadData = () => {
    this.setState({
      isLoading: true,
      pageNo: 1,
      writeOffList: [],
      showFoot: 0
    }, () => {
      this.findGvrOilRecord('pullDown');
    });
  }

  // 上拉加载更多
  LoadMore = () => {
    this.setState({ showFoot: 2 }, () => {
      this.findGvrOilRecord('pullUp');
    });
  }

  findGvrOilRecord = (type) => {
    const { pageNo, pageSize, writeOffList, siteDetails } = this.state;
    let newWriteOffList = [];
    oil.findGvrOilRecord({ pageNo, pageSize, siteNo: siteDetails.siteNo }).then(res => {
      if (res.success) {
        const { records, pages } = res.data;
        if (type === 'pullDown') {
          this.setState({ writeOffList: records });
        }
        if (type === 'pullUp') {
          if (pageNo > pages) {
            this.setState({ showFoot: 1 });
            return;
          }
          newWriteOffList = [...writeOffList, ...records];
          this.setState({ writeOffList: newWriteOffList });
        }
        this.setState({ isLoading: false, pageNo: pageNo + 1 });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }
}

const styles = StyleSheet.create({
  headTitleText: {
    color: '#000',
    fontSize: 18,
    fontWeight: isAndroid ? '400' : 'bold',
  },
  headRight: {
    maxWidth: px2dp(250),
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: px2dp(14 * 2)
  },
  headRightImage: {
    width: px2dp(32),
    height: px2dp(32),
    marginRight: px2dp(5)
  },
  headRightText: {
    fontSize: px2dp(28),
    color: fontColorBlack,
  },
  titleTips: {
    height: px2dp(96),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: px2dp(24),
    backgroundColor: mainBgColorLightGray
  },
  titleTipsRightImage: {
    width: px2dp(24),
    height: px2dp(24)
  },
  xmListContainer: {
    backgroundColor: mainBgColorLightGray,
    paddingHorizontal: px2dp(24),
  },
});
